#pragma once

#include <iostream>
#include <sys/time.h>
#include "Socket.hpp"
#include <sys/select.h>


using namespace std;

const uint16_t defaultport = 8888;     // 默认端口
const int fd_max = sizeof(fd_set) * 8; // 打开文件的最大数目
int defaultfd = -1;

class Selectserver
{
public:
    Selectserver()
    {
        for (int i = 0; i < fd_max; i++)
        {
            fds_array[i] = defaultfd; // 文件描述符数组的初始化为-1；
        }
    }

    bool Init()
    {
        listensock_.Socket();
        listensock_.Bind(defaultport);
        listensock_.Listen();
        return true;
    }

    void Accpter()
    {
        string ip;
        uint16_t port;
        int sock = listensock_.Accpect(&ip, &port);
        if (sock < 0)
            return ; // 出错了，本次退出

        lg("info", "accpect success ip=%s port=%d fd=%d", ip, port, sock);

        int i = 1; // 第一个一定会是listensock
        for (; i < fd_max; i++)
        {
            if (fds_array[i] != defaultfd)
                continue;
            else
                break;
        }
        if (i == fd_max)
        {
            lg("Warning", "server full close %d", sock);
            close(sock);
        }
        else
        {
            fds_array[i] = sock;
            // 打印
            Print();
        }
    }

    void Recver(int fd, int pos) // 文件描述符，数组占的下标
    {
        char buffer[1024]; // tcp 多次读取，此处不合格的

        int n = read(fd, buffer, sizeof(buffer) - 1);
        if (n < 0)
        {
            lg("Warning","recver error");
            fds_array[pos] = defaultfd;
            close(fd);
        }
        else if (n == 0)
        {
            lg("info", "client close");
            fds_array[pos] = defaultfd;
            close(fd);
        }
        else
        {
            buffer[n] = 0;
            cout << "get a message" << buffer << endl;
        }
    }

    void Dispatch(fd_set &rfds)
    {
        for (int i = 0; i < fd_max; i++)
        {
            int fd = fds_array[i];
            if (fd == defaultfd)
                continue;

            if (FD_ISSET(fd, &rfds))
            {
                if (fd == listensock_.Fd())
                {
                    Accpter();
                }
                else
                {
                    Recver(fd, i);
                }
            }
        }
    }

    void Start()
    {
        fd_set rfds;
        int listensock = listensock_.Fd();
        for (;;)
        {
            FD_ZERO(&rfds); // 初始化
            fds_array[0] = listensock;//还有别的连接到来，重写放到数组

            int maxfd = listensock;
            for (int i = 0; i < fd_max; i++)
            {
                if (fds_array[i] != defaultfd)
                {
                    FD_SET(fds_array[i], &rfds); // 重置
                }
                else
                    continue;
                if (fds_array[i] > maxfd)
                {
                    maxfd = fds_array[i];
                }
            }

            struct timeval timeout = {2, 0};
            int n = select(maxfd + 1, &rfds, NULL, NULL, &timeout);
            switch (n)
            {
            case -1:
                cerr << "select error" << endl;
                break;
            case 0:
                cout << "time out no ready" << endl;
                break;
            default:
                Dispatch(rfds);//listen或者数据来了
                break;
            }
        }
    }

    void Print()
    {
        cout<<"online link"<<endl;
        for(int i=0;i<fd_max;i++)
        {
            if(fds_array[i]==defaultfd)
            continue;
            else printf("%d ",fds_array[i]);
        }
        cout<<endl;
    }

    ~Selectserver()
    {
        close(listensock_.Fd());
    }

private:
    Sock listensock_;
    int fds_array[fd_max];
};
